import { selectPhone } from "./api";
import $ from "jquery";

$("#selectPhoneClose").on("click", () => {
  toggleSelectPhone();
});

$(".ui-phone-mask").on("transitionend", () => {
  if ($(".ui-phone-mask").hasClass("hide")) {
    $(".ui-phone-mask").hide();
    $("body").css("overflow", "auto");
    $("#searchPhoneSearch").val("");
  }
});

let searchParam = {
  channel: "",
  phoneCityCode: "",
  phoneCityName: "",
  phoneProvinceCode: "",
  phoneProvinceName: "",
  searchParam: "",
  searchValue: "",
};

/**@type {(data?: {number: string, uuid: string})=>void} */
let callback = null;

$("#searchPhoneSearch").on("change", () => {
  searchParam.searchValue = $("#searchPhoneSearch").val();
});

async function reload() {
  $("#phone-list>*").remove();

  const result = await selectPhone(searchParam);
  const numbers = result.dataList;
  for (let i = 0; i < numbers.length; i += 2) {
    const first = numbers[i];
    const second = numbers[i + 1];

    const tag = $('<div class="row"></div>');
    const firstTag = $(`<div class="item">
      <div class="number">${first.number}</div>
      <div class="row">
        <div class="price">￥${first.price}</div>
        <div class="free">限时免费</div>
      </div>
    </div>`);

    const secondTag = $(`<div class="item">
      <div class="number">${second.number}</div>
      <div class="row">
        <div class="price">￥${second.price}</div>
        <div class="free">限时免费</div>
      </div>
    </div>`);

    firstTag.on("click", () => {
      callback({
        number: first.number,
        uuid: result.uuid,
      });
      toggleSelectPhone();
    });
    secondTag.on("click", () => {
      callback({
        number: second.number,
        uuid: result.uuid,
      });
      toggleSelectPhone();
    });

    tag.append(firstTag).append(secondTag);
    $("#phone-list").append(tag);
  }
}

$("#searchPhoneSearchBtn").on("click", reload);
$("#changePhoneBtn").on("click", reload);

/**
 *
 * @param {{
 * phoneCityCode: string,
 * phoneCityName: string,
 * phoneProvinceCode: string,
 * phoneProvinceNam: string,
 * channel : string,
 * searchParam?: string,
 * searchValue?: string,
 * callback: (data?: {number: string, uuid: string})=>void
 * }} [params]
 */
export function toggleSelectPhone(params) {
  if (params) {
    callback = params.callback;
    delete params.callback;
    searchParam = params;
  }
  if ($(".ui-phone-mask").hasClass("hide")) {
    $(".ui-phone-mask").show();
    $("body").css("overflow", "hidden");
    reload();
  }
  $(".ui-phone-mask").toggleClass("hide");
}
